
import { onHide } from '@dcloudio/uni-app';
import { ref, onBeforeUnmount } from 'vue';

/** 课程还有5分钟倒计时 */
const useCountdown = () => {
	/** 计时器 */
	const timer = ref(null);
	
	/** 清除计时器 */
	const clearIntervalTime = () => {
		clearInterval(timer.value);
		timer.value = null;
	};
	
	/** 开始计时 */
	const startSetInterval = (options?: { time: string, callback: () => void, learnType: number }) => {
		const courseData = uni.getStorageSync('_course-date') || {};
		const { time = courseData?.finishTime, callback, learnType = courseData.learnType } = options || {};
		if (!time || learnType == 1) return;
		let newdate = 0;
		const setIntervalCallback = () => {
			const date = new Date();
			const endDate = Date.parse(time);
			const startDate = Date.parse(date as unknown as string);
			newdate = endDate - startDate;
			console.log('newdate', newdate);
			newdate < 0 && clearIntervalTime();
			if (newdate === 0) {
				clearIntervalTime();
				uni.showModal({ 
					title: '温馨提示', 
					showCancel: false, 
					confirmText: '学后检测' ,
					success: ({ confirm }) => confirm && callback?.(),
					content: '当前课程已结束，请进入学后检测提交课程学习成果！'
				});
			};
					
			if (newdate === 300000) uni.showModal({ title: '温馨提示', content: '课程还有5分钟结束，请尽快提交学后检测！', showCancel: false, confirmText: '关闭' });
		};
		
		setIntervalCallback();
		if (newdate > 0) timer.value = setInterval(setIntervalCallback, 1000);
	};
	
	onBeforeUnmount(() => {
		clearIntervalTime();
	});
	
	onHide(() => {
		clearIntervalTime();
	});
	
	
	return { startSetInterval, clearIntervalTime };
};


export default useCountdown;